﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.EnvironmentVariables;
using Microsoft.Extensions.Configuration.CommandLine;
using Microsoft.Extensions.Configuration.Memory;
using Microsoft.Extensions.Configuration.Xml;
using Microsoft.Extensions.Configuration.Ini;
using Microsoft.Extensions.Configuration.Binder;
using Microsoft.Extensions.Configuration.KeyPerFile;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.Configuration.UserSecrets;

using Microsoft.Extensions.Options; 

using NetEscapades.Configuration.Yaml;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace HttpClientStudy.Config
{
    public static class WebApiConfigExtensions
    {
        /// <summary>
        /// 添加WebApi配置文件
        /// </summary>
        public static IConfigurationBuilder AddWebApiConfiguration(this IConfigurationBuilder configuration)
        {
            //配置文件名称
            configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            configuration.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true, reloadOnChange: true);
            //配置文件根目录：配置项目Dll文件所在目录(被其它项目引用时，引用后dll的文件所在目录)
            string configDellPath = Path.GetDirectoryName(typeof(WebApiConfig).Assembly.Location) ?? Directory.GetCurrentDirectory();
            configuration.SetBasePath(configDellPath);
            Console.WriteLine($"配置文件根目录：{configDellPath}");

            configuration.AddJsonFile($"ConfigFiles/Config.json", optional: false, reloadOnChange: true);
            configuration.AddJsonFile($"ConfigFiles/Config.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true, reloadOnChange: true);

            return configuration;
        }

        /// <summary>
        /// 使用选项模式 
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <returns></returns>
        public static IServiceCollection UseWebApiOptions(this IServiceCollection services)
        {
            services.AddOptions();

            var configuration = services.BuildServiceProvider().GetService<IConfiguration>();
            if (configuration == null)
            {
                throw new InvalidOperationException("Configuration is not configured.");
            }

            services.Configure<WebApiConfig>(configuration.GetSection("WebApi"));

            return services;
        }
    }
}
